<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\cdc\append;

use app\enum\CommonEnum;
use app\enum\ServiceCostEnum;
use app\model\mongo\MongoInfoModel;
use app\model\mongo\MongoKsPicAppendSyncLogModel;
use app\model\mongo\MongoStatModel;
use app\model\mongo\MongoSyncModel;
use app\service\cdc\PicService;
use app\service\cdc\sync\KsPicAppendSyncLogService;

class KsPicAppendService extends PicAppendService implements PicInterface
{
    protected int $mediaId = CommonEnum::KS_MEDIA;

    protected ?MongoSyncModel $syncModel;

    protected ?MongoInfoModel $infoModel;

    protected ?MongoStatModel $statModel;

    /**
     * 获取中间表模型.
     */
    public static function getSyncModel(): MongoSyncModel
    {
        return new MongoKsPicAppendSyncLogModel();
    }

    /**
     * 运行数据模型.
     */
    public function runStat(MongoSyncModel $model): bool
    {
        $this->syncModel = $model;
        $lockKey = sprintf(ServiceCostEnum::CACHE_CONFIG['media_pic_append_cost_lock'][CommonEnum::KS_MEDIA], strval($this->syncModel->getKey()));
        if (self::lock($lockKey, 1, 120)) {
            if (! $this->setModel()) {
                return false;
            }

            return $this->appendStat();
        }
        return self::setError('加锁失败！lock_key:' . $lockKey);
    }

    /**
     * 新增日志.
     */
    public static function addLogByInfo(MongoInfoModel $model): bool
    {
        $statDate = intval(date('Ymd', $model->getAttr('create_time')));
        return PicService::addSyncLog(static::getSyncModel(), [
            'client_id' => $model->getAttr('client_id'),
            'account_id' => $model->getAttr('account_id'),
            'adv_id' => $model->getAttr('adv_id'),
            'signature' => $model->getAttr('signature'),
            'pic_id' => $model->getAttr('pic_id'),
            'cost' => 0,
            'stat_date' => $statDate,
            'version' => $statDate,
            'type' => $model->getAttr('type'),
            'user_id' => $model->getAttr('user_id') ?? '',
        ]);
    }

    /**
     * 获取列表.
     * @return mixed
     */
    public static function getList(int $num = 0)
    {
        return KsPicAppendSyncLogService::getList($num);
    }
}
